<template>
  <el-select
    v-model="l_userid"
    filterable
    remote
    reserve-keyword
    placeholder="请输入关键词"
    :remote-method="userSearch"
    :loading="loading"
    :disabled="disabled"
    @change="selectChanged"
  >
    <el-option v-for="item in users" :key="item.AutoId" :label="item.Name" :value="item.AutoId">
      <span style="float: left">{{ item.Name }}</span>
      <span style="float: right; color: #8492a6; font-size: 13px">{{ item.Code }}</span>
    </el-option>
  </el-select>
</template>

<script>
import { searchUser } from '@/api/user'

export default {
  data() {
    return {
      loading: false,
      users: [],
      l_userid: null
    }
  },
  model: {
    prop: 'userId',
    event: 'userSelected'
  },
  props: ['userId', 'disabled'],
  mounted() {
    this.search('%')
    this.l_userid = this.userId
  },
  watch: {
    userId: function(value) {
      this.l_userid = value
    }
  },
  methods: {
    search(keywords) {
      searchUser(keywords)
        .then(response => {
          this.users = response.Data
        })
        .catch(error => {
          console.log(error)
          this.users = []
        })
    },
    userSearch(query) {
      if (query !== '') {
        this.loading = true
        setTimeout(() => {
          this.loading = false
          this.search(query)
        }, 200)
      } else {
        this.users = []
      }
    },
    selectChanged(params) {
      this.$emit('userSelected', params)
    }
  }
}
</script>